import axios from 'axios';
import qs from 'qs'
const instance = axios.create({
    timeout: 1000 * 60,
    withCredentials: true,
    validateStatus: status => {
        return status >= 200 && status < 300; // default
    },
    baseURL: 'http://api.cpengx.cn/metashop/api'
});

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    return config;
}, function (error) {
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    return Promise.reject(error);
});

function request({ url, method = 'GET', params = {} }) {
  return new Promise((resolve, reject) => {
    method = method.toLowerCase();
    const requestBody = method === 'get' ? 'params' : 'data';
    const format = method === 'get' ? params : qs.stringify(params);
    const result = instance({ url, method, [requestBody]: format});
    result.then(value => resolve(value.data), reason => console.log(reason));
  });
};

export default request;